<script lang="ts" setup>
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { oneClickRefund } from '@fl/api/order/base'
import { couponDataPage, couponEnable, getBusinessBlocksList } from '@fl/api/anjutong'
import { useQueryOrderList } from '@fl/api/anjutong/seckill-manage'
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { useRouter } from 'vue-router'

import { couponInfo } from './type'
import { formatTime } from '@fl/utils'

const refundFormRef = ref(null)
const refundDialog = ref(false)
const refundForm = reactive({
    spikeQualificationFee: '',
    reason: '',
    id: '',
})
const router = useRouter()

const initialState = {
    orderNumber: '',
    customerName: '',
    buildingContactPerson: '',
    buildingName: '',
    orderStatus: '',
    submissionStartDate: '',
    submissionEndDate: '',
    payStartDate: '',
    payEndDate: '',
    submissionDate: [],
}
const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}
const tablePage = ref(cloneDeep(initialPage))
const businessModulesList = ref([])
const plate = ref()
const state = ref(cloneDeep(initialState))
const searchConditions = ref(cloneDeep(initialState))
const tableData = ref([])
const columns = ref([
    {
        colProps: {
            span: 6,
        },
        label: '订单编号',
        prop: 'orderNumber',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '客户名称',
        prop: 'customerName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '楼盘对接人',
        prop: 'buildingContactPerson',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '楼盘名称',
        prop: 'buildingName',
        valueType: 'copy',
    },
    {
        colProps: {
            span: 6,
        },
        label: '订单状态',
        options: [
            {
                label: '已下单',
                value: 1,
            },
            {
                label: '已付款',
                value: 2,
            },
            /* {
                label: '已签约',
                value: 3,
            }, */
            {
                label: '已关闭',
                value: 4,
            },
            {
                label: '已退款',
                value: 5,
            },
        ],
        prop: 'orderStatus',
        valueType: 'select',
    },
    {
        colProps: {
            span: 8,
        },
        fieldProps: {
            endPlaceholder: '请选择结束时间',
            format: 'YYYY-MM-DD',
            startPlaceholder: '请选择开始时间',
            type: 'daterange',
        },
        label: '提交时间',
        prop: 'submissionDate',
        valueType: 'date-picker',
    },

])

const gridOptions = reactive<VxeGridProps>({
    columns: [
        { title: '序号', type: 'seq', width: 70 },
        { field: 'orderNumber', minWidth: 180, title: '订单编号' },
        { field: 'houseAddress', minWidth: 200, title: '房源地址' },
        { field: 'houseType', minWidth: 100, title: '户型' },
        { field: 'area', minWidth: 100, title: '面积(m2)' },
        { field: 'sellingPrice', minWidth: 100, title: '售价' },
        { field: 'fixedPrice', minWidth: 100, title: '一口价' },
        { field: 'buildingContactName', minWidth: 100, title: '楼盘对接人' },
        { field: 'customerName', minWidth: 100, title: '客户姓名' },
        { field: 'contactInfo', minWidth: 150, title: '联系方式' },
        { field: 'spikeQualificationFee', minWidth: 100, title: '秒杀资格金' },
        { field: 'paymentMethod', minWidth: 100, slots: { default: 'paymentMethod' }, title: '支付方式' },
        { field: 'submissionTime', minWidth: 150, title: '提交时间' },
        { field: 'paymentTime', minWidth: 150, title: '支付时间' },
        { field: 'orderStatus', minWidth: 150, slots: { default: 'orderStatus' }, title: '订单状态' },
        { fixed: 'right', minWidth: 140, slots: { default: 'operate' }, title: '操作' },
    ],
})

const dialogVisible = ref(false)
const couponId = ref()

// init()

/**
 * methods start
 */

// function init() {
//     getDataList()
// }

// 查询列表
const params = computed(() => ({
    submissionStartDate: searchConditions.value.submissionDate?.[0] ? formatTime(searchConditions.value?.submissionDate[0], 'yyyy-MM-dd 00:00:00') : undefined,
    submissionEndDate: searchConditions.value.submissionDate?.[1] ? formatTime(searchConditions.value?.submissionDate[1], 'yyyy-MM-dd 23:59:59') : undefined,
    orderNumber: searchConditions.value.orderNumber ? searchConditions.value.orderNumber : undefined,
    customerName: searchConditions.value.customerName ? searchConditions.value.customerName : undefined,
    buildingContactPerson: searchConditions.value.buildingContactPerson ? searchConditions.value.buildingContactPerson : undefined,
    buildingName: searchConditions.value.buildingName ? searchConditions.value.buildingName : undefined,
    orderStatus: searchConditions.value.orderStatus ? searchConditions.value.orderStatus : undefined,
    pageNum: tablePage.value.currentPage,
    pageSize: tablePage.value.pageSize,
}))
const { data, isLoading, refetch } = useQueryOrderList(params)
watchEffect(() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value.rows)
        tablePage.value.total = data.value.total
    }
})

// 获取折扣劵列表
// function getDataList() {
//     queryOrderList({
//         orderNumber: state.value.orderNumber,
//         customerName: state.value.customerName,
//         pageNum: tablePage.value.currentPage,
//         pageSize: tablePage.value.pageSize,
//     }).then((res) => {
//         tableData.value = res.rows
//         tablePage.value.total = res.total
//     })
// }

function resetSearch() {
    state.value = cloneDeep(initialState)
    searchConditions.value = cloneDeep(initialState)
    plate.value = undefined
    // getDataList()
}

function submitSearch() {
    searchConditions.value = cloneDeep(state.value)
    tablePage.value.currentPage = 1
    // getDataList()
}

function showData(row) {
    couponId.value = row.id
    dialogVisible.value = true
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
    // getDataList()
}

// 跳转详情（新增、编辑）页面
function toPage(name, type, row) {
    const id = type === 'add' ? 'item' : row.id
    router.push({ name, params: { id, type } })
}

// 启用/禁用优惠券
// function setStatus(row) {
//     couponEnable({ id: row.id }).then(() => {
//         ElMessage.success('操作成功')
//         getDataList()
//     })
// }

function handleClose() {
    refundDialog.value = false
    refundForm.reason = ''
    refundForm.id = ''
    refundForm.spikeQualificationFee = ''
}

const refundRules = reactive({
    reason: [
        { required: true, message: '请输入退款原因', trigger: 'blur' },
        { min: 1, max: 50, message: '长度不超过50字', trigger: 'blur' },
    ],
})

function handleConfirm() {
    if (refundFormRef.value) {
        refundFormRef.value?.validate((valid) => {
            if (valid) {
                const params = {
                    id: refundForm.id,
                    refundMethod: '1',
                    refundAmount: refundForm.spikeQualificationFee,
                    reasonForCancellation: refundForm.reason,
                }
                oneClickRefund(params).then((res) => {
                    if (res.code == '200') {
                        ElMessage.success('操作成功')
                        handleClose()
                        refetch()
                    }
                    else {
                        ElMessage.warning(res.msg)
                    }
                })
            }
        })
    }
}

function oneClick(row) {
    refundForm.id = row.orderId
    refundForm.reason = ''
    refundForm.spikeQualificationFee = row.spikeQualificationFee
    refundDialog.value = true
}

/**
 * methods end
 */
</script>

<template>
    <div class="activity-coupon-manage">
        <ElCard class="mb-20"
                shadow="never"
        >
            <SearchForm v-model="state"
                        :columns="columns"
                        submit-text="搜索"
                        @reset="resetSearch"
                        @submit="submitSearch"
            >
                <template #plus-field-plate>
                    <el-select v-model="plate">
                        <el-option v-for="item in businessModulesList"
                                   :key="item.value"
                                   :label="item.label"
                                   :value="item.value"
                                   :disabled="item.disabled"
                        />
                    </el-select>
                </template>
            </SearchForm>
        </ElCard>

        <ElCard shadow="never">
            <SearchTable v-bind="gridOptions"
                         v-model:pager="tablePage"
                         :loading="isLoading"
                         :data="tableData"
                         @page-change="handlePageChange"
            >
                <template #toolbar_buttons>
                    <!-- 显示按钮
                    <el-button plain
                               type="primary"
                               @click="toPage('discount-manage-detail', 'add')"
                    >
                        新增
                    </el-button> -->
                </template>
                <!-- 0 未支付。WXPay 微信支付。Alipay 2.0  支付宝支付 -->
                <template #paymentMethod="{ row }">
                    <span v-if="row.paymentMethod == '0'">未支付</span>

                    <span v-if="row.paymentMethod == 'WXPay'">微信支付</span>

                    <span v-if="row.paymentMethod == 'Alipay 2.0'">支付宝支付</span>
                </template>

                <!--
                订单状态，
                1：已下单，未付款，zdgbsj为系统自动关闭时间
                2：已付款 （shzt（一审状态）或eszt（二审状态）不为空则表示定单在走审核流程，若一审二审状态都为空，表示尚未开始审核，未在24小时内审核的，会自动退单）
                若，订单中退款方式或退款金额不为空，则已经在走退款审核流程
                3：已签约，订单已完成签约流程
                4：已关闭，closeRemark字段返回关闭原因
                5：已取消，reasonForCancellation取消原因
                -->
                <template #orderStatus="{ row }">
                    <span v-if="row.orderStatus === '1'">已下单，未付款</span>

                    <span v-if="row.orderStatus === '2'">已付款</span>

                    <!-- <span v-if="row.orderStatus === '3'">已签约</span> -->

                    <span v-if="row.orderStatus === '4'">已关闭</span>

                    <span v-if="row.orderStatus === '5'">已退款</span>
                </template>

                <template #operate="{ row }">
                    <div class="operate-btns">
                        <el-button v-if="row.orderStatus === '2'"
                                   type="primary"
                                   text
                                   @click="oneClick(row)"
                        >
                            退款
                        </el-button>
                    </div>
                </template>
            </SearchTable>
        </ElCard>
    </div>

    <el-dialog v-model="refundDialog"
               title="退款"
               destroy-on-close
               @before-close="handleClose"
    >
        <ElForm ref="refundFormRef"
                :model="refundForm"
                :rules="refundRules"
                label-width="120px"
                class="demo-ruleForm"
                status-icon
                style="background-color: white;margin: 0 auto;width: 100%;padding: 20px;"
        >
            <el-form-item label="退款原因:"
                          prop="reason"
            >
                <el-input v-model="refundForm.reason"
                          type="textarea"
                          maxlength="50"
                          show-word-limit
                          :autosize="{ minRows: 3, maxRows: 5 }"
                          placeholder="请输入退款原因"
                />
            </el-form-item>

        <!-- <el-form-item label="订金订单金额:"
                          prop="deposit"
            >
                <el-text>¥{{ deposit }}</el-text>
            </el-form-item>

            <el-form-item label="确认退款金额:"
                          prop="refundAmount"
            >
                <el-input v-model="form.refundAmount"
                          placeholder=""
                />
            </el-form-item> -->
        </ElForm>

        <template #footer>
            <div style="text-align: right;">
                <el-button @click="handleClose">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="handleConfirm"
                >
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
.coupon-data-dialog {
}
:deep(.coupon-data-dialog .el-dialog) {
    height: calc(100vh - 120px) !important;
}
:deep(.coupon-data-dialog .el-dialog__body) {
    overflow: hidden;
    overflow-y: auto;
}
:deep(.operate-btns .el-button) {
    margin: 0;
    padding: 6px;
}
</style>
